package com.spddr.pmos.cxf.impl;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import com.spddr.pmos.cxf.JaxrsUser;
import com.spddr.pmos.jpa.Role;
import com.spddr.pmos.jpa.User;
import com.spddr.pmos.jpa.UserRole;
import com.spddr.pmos.repos.UserRepos;
import com.spddr.pmos.repos.UserRoleRepos;

@Service
public class JaxrsUserImpl extends AbstractJaxrsObjectImpl<User> implements JaxrsUser {
	@Autowired
	private UserRepos repository;
	@Autowired
	private UserRoleRepos urRepos;

	@Override
	public JpaRepository<User, Long> getRepository() {
		return repository;
	}

	@Override
	public List<Role> findRoles(long id) {
		return urRepos.findByIdUser(id)
				.stream()
				.map(x -> x.getRole())
				.collect(Collectors.toList());
	}

	@Override
	public List<Role> saveRoles(long id, List<Role> roles) {
		List<UserRole> entities = roles.stream()
				.map(x -> new UserRole(id, x.getId()))
				.collect(Collectors.toList());
		entities = urRepos.save(entities);
		return entities.stream()
				.map(x -> x.getRole())
				.collect(Collectors.toList());
	}

	@Override
	public void deleteRoles(long id) {
		urRepos.deleteByUser(id);
	}
}
